package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper,Brand> implements BrandService {

   private final CategoryBrandService categoryBrandService;

    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }


    /**
     * 根据id查询品牌
     * @param id
     * @return
     */
    @Override
    public BrandDTO findBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }

    /**
     * 分页查询品牌
     * @param page
     * @param rows
     * @param key
     * @return
     */
    @Override
    public PageDTO<BrandDTO> pageQuery(Integer page, Integer rows, String key) {
        IPage iPage = new Page(page,rows);
        boolean condition = StringUtils.isNotBlank(key);
        page(iPage,new QueryWrapper <Brand>()
                .like(condition,"name",key)
                .or()
                .eq(condition,"little",key));

        List brands = BrandDTO.convertEntityList(iPage.getRecords());

        return new PageDTO <BrandDTO>(iPage.getTotal(),iPage.getPages(),brands);
    }

    /**
     * 根据id集合查询品牌
     * @param ids
     * @return
     */
    @Override
    public List <BrandDTO> listBrandByIds(List <Long> ids) {

        return BrandDTO.convertEntityList(this.listByIds(ids));
    }


    /**
     *
     * @param cid
     * @return
     */
    @Override
    public List <BrandDTO> listBrandByCategory(Long cid) {

        //根据分类id查询中间表对象获取到品牌的id集合，然后根据品牌的id集合查询对应的品牌集合
        List <CategoryBrand> categoryBrands = this.categoryBrandService
                .query()
                .eq("category_id", cid)
                .list();
        if (CollectionUtils.isEmpty(categoryBrands)){
            throw new LyException(204,"当前分类没有关联品牌");
        }


        return listBrandByIds(categoryBrands.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);

        this.save(brand);
        if (CollectionUtils.isEmpty(brandDTO.getCategoryIds())){
            throw new LyException(400,"此品牌对应分类不能为空");
        }
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());

    }

    private void saveCategoryBrand(List<Long> cids, Long  bid) {
        //根据分类id集合和品牌id，组合出中间表
        List<CategoryBrand> categoryBrands = cids
                .stream()
                .map(id -> CategoryBrand.of(id, bid))
                .collect(Collectors.toList());
        //保存中间表数据
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //根据id修改品牌信息
        this.updateById(brand);
        //品牌分类是否有修改的问题，多，少，没变
        //删除当前分类信息
        this.categoryBrandService.remove(new QueryWrapper <CategoryBrand>().eq("brand_id",brand.getId()));
        //重新建立关系
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

    /*

        //根据分类id查询中间表对象获取到品牌的id集合，然后根据品牌的id集合查询对应的品牌集合
        List<CategoryBrand> categoryBrands = this.categoryBrandService
                .query()
                .eq("category_id", cid)
                .list();

        if (CollectionUtils.isEmpty(categoryBrands)) {

            throw new LyException(204, "当前分类没有关联品牌");
        }


        return listBrandByIds(categoryBrands.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList()));
    }*/
}
